/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "set_key_event_plugin.h"

#include <algorithm>

#include "app_control/app_control_proxy.h"
#include <bundle_mgr_interface.h>
#include <system_ability_definition.h>

#include "edm_constants.h"
#include "edm_ipc_interface_code.h"
#include "edm_sys_manager.h"
#include "element_name.h"
#include "iplugin_manager.h"
#include "ipolicy_manager.h"
#include "func_code_utils.h"
#include "set_key_event_serializer.h"
#include "preference_manager.h"
#include "array_int_serializer.h"

namespace OHOS {
namespace EDM {


const bool REGISTER_RESULT =
    IPluginManager::GetInstance()->AddPlugin(std::make_shared<SetKeyEventPlugin>());

SetKeyEventPlugin::SetKeyEventPlugin()
{
    policyCode_ = EdmInterfaceCode::SET_KEY_EVENT_POLICYS;
    policyName_ = PolicyName::POLICY_SET_KEY_EVENT;
    permissionConfig_.typePermissions.emplace(IPlugin::PermissionType::SUPER_DEVICE_ADMIN,
        EdmPermission::PERMISSION_ENTERPRISE_MANAGE_SYSTEM);
    permissionConfig_.apiType = IPlugin::ApiType::PUBLIC;
    needSave_ = true;
}

ErrCode SetKeyEventPlugin::OnHandlePolicy(std::uint32_t funcCode, MessageParcel &data,
    MessageParcel &reply, HandlePolicyData &policyData, int32_t userId)
{
    EDMLOGI("SetKeyEventPlugin OnHandlePolicy.");
    uint32_t typeCode = FUNC_TO_OPERATE(funcCode);
    FuncOperateType type = FuncCodeUtils::ConvertOperateType(typeCode);
    std::vector<KeyCustomization> currentData;
    SetKeyEventsSerializer::GetInstance()->Deserialize(policyData.policyData, currentData);
    std::vector<KeyCustomization> mergeData;
    SetKeyEventsSerializer::GetInstance()->Deserialize(policyData.mergePolicyData, mergeData);
    std::string mergePolicyStr;
    IPolicyManager::GetInstance()->GetPolicy("", GetPolicyName(), mergePolicyStr, userId);
    ErrCode res = EdmReturnErrCode::PARAM_ERROR;
    if (type == FuncOperateType::SET) {
        PreferenceManager preferenceManager;
        std::string keyEventStr = preferenceManager.GetSupportedKeyCodes();
        std::vector<int32_t> tempData;
        ArrayIntSerializer::GetInstance()->Deserialize(keyEventStr, tempData);
        std::vector<KeyCustomization> KeyCustomizations;
        KeyEventHandle::ReadKeyCustomizationVector(data, KeyCustomizations);
        for (const auto& element : KeyCustomizations) {
            if (std::find(tempData.begin(), tempData.end(), element.keyEvent) == tempData.end() ||
                element.keyPolicy != static_cast<int32_t>(KeyPolicy::INTERCEPTION) ||
                element.keyPolicy != static_cast<int32_t>(KeyPolicy::CUSTOM)) {
                    return EdmReturnErrCode::PARAMETER_VERIFICATION_FAILED;
                }
            }
        res = OnSetPolicy(KeyCustomizations, currentData, mergeData);
    } else if (type == FuncOperateType::REMOVE) {
        std::vector<int32_t> keyEvents;
        data.ReadInt32Vector(&keyEvents);
        res = OnRemovePolicy(keyEvents, currentData, mergeData);
    }
    if (res != ERR_OK) {
        reply.WriteInt32(res);
        return res;
    }
    reply.WriteInt32(ERR_OK);
    std::string afterHandle;
    std::string afterMerge;
    SetKeyEventsSerializer::GetInstance()->Serialize(currentData, afterHandle);
    SetKeyEventsSerializer::GetInstance()->Serialize(mergeData, afterMerge);
    policyData.isChanged = (policyData.policyData != afterHandle || mergePolicyStr != afterMerge);
    policyData.policyData = afterHandle;
    policyData.mergePolicyData = afterMerge;
    return ERR_OK;
}

ErrCode SetKeyEventPlugin::OnSetPolicy(std::vector<KeyCustomization> &keyCustomizations,
    std::vector<KeyCustomization> &currentData, std::vector<KeyCustomization> &mergeData)
{
    EDMLOGI("SetKeyEventPlugin OnSetPolicy");
    //自身冲突比较，有直接返回9200010
    for (size_t i = 0; i < keyCustomizations.size(); ++i) {
        for (size_t j = i + 1; j < keyCustomizations.size(); ++j) {
            if (keyCustomizations[i].keyEvent == keyCustomizations[j].keyEvent &&
                keyCustomizations[i].keyPolicy != keyCustomizations[j].keyPolicy) {
                // 存在冲突
                return EdmReturnErrCode::CONFIGURATION_CONFLICT_FAILED;
            }
        }
    }
    //和merger比较，有相同键报9200010
    for (const KeyCustomization &dataItem : keyCustomizations) {
        for (const KeyCustomization &item : mergeData) {
            if (item.keyEvent ==  dataItem.keyEvent) {
                // 存在冲突
                return EdmReturnErrCode::CONFIGURATION_CONFLICT_FAILED;
            }
        }
    }
    //和current比较，存在对应键，覆盖，没有对应键添加到current，同时保存到merge
    for (const KeyCustomization &dataItem : keyCustomizations) {
        for (KeyCustomization &item : currentData) {
            if (item.keyEvent ==  dataItem.keyEvent) {
                item.keyEvent = dataItem.keyEvent;
                item.keyPolicy = dataItem.keyPolicy;
            } else {
                currentData.push_back(dataItem);
            }
        }
    }
    for (const KeyCustomization &item : currentData) {
        mergeData.push_back(item);
    }
    return ERR_OK;
}

ErrCode SetKeyEventPlugin::OnRemovePolicy(std::vector<int> &keyEvents,
    std::vector<KeyCustomization> &currentData, std::vector<KeyCustomization> &mergeData)
{
    EDMLOGI("SetKeyEventPlugin::OnRemovePolicy");
    if (keyEvents.empty()) {
        EDMLOGW("SetKeyEventPlugin OnRemovePolicy keyEvents is empty.");
        return ERR_OK;
    }
    //和current比较，如存在对应键，删除，同时保存merger
    std::vector<KeyCustomization> temData;
    for (const auto &it : keyEvents) {
        for (const KeyCustomization &item : currentData) {
            if (it != item.keyEvent) {
                temData.push_back(item);
            }
        }
    }
    currentData = temData;
    for (const KeyCustomization &item : currentData) {
        mergeData.push_back(item);
    }
    return ERR_OK;
}

ErrCode SetKeyEventPlugin::OnGetPolicy(std::string &policyData, MessageParcel &data,
    MessageParcel &reply, int32_t userId)
{
    EDMLOGI("SetKeyEventPlugin OnGetPolicy");
    std::string type = data.ReadString();
    std::vector<KeyCustomization> keyEventsInfo;
    SetKeyEventsSerializer::GetInstance()->Deserialize(policyData, keyEventsInfo);
    std::vector<KeyCustomization> policy;
    for (const KeyCustomization &item : keyEventsInfo) {
        KeyCustomization instance;
        instance.keyEvent = item.keyEvent;
        instance.keyPolicy = item.keyPolicy;
        policy.emplace_back(std::move(instance));
    }
    reply.WriteInt32(ERR_OK);
    KeyEventHandle::WriteKeyCustomizationVector(reply, policy);
    return ERR_OK;
}

ErrCode SetKeyEventPlugin::OnAdminRemove(const std::string &adminName, const std::string &currentJsonData,
    const std::string &mergeJsonData, int32_t userId)
{
    return EdmReturnErrCode::CONFIGURATION_CONFLICT_FAILED;
}

} // namespace EDM
} // namespace OHOS